<?php
namespace app\admin\controller;

use think\facade\View;
use app\validate\User as Abc;
use think\exception\ValidateException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT as JWTUtil;
use Firebase\JWT\Key;
use app\admin\model\User;
use app\admin\model\Miniuser;
use think\facade\Db;

class Total
{
    // protected $middleware = [\app\middleware\Login::class];
    public $jwt_secret_key = "i7H98G6jJK7YIbT599GB";
    public $user = array("name" => "zhangWei", "age" => "35");//用户名
    public $exptime = 20;
    public $tokenContent = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImtpZCI6ImtleUlkIn0.eyIwIjp7Im5hbWUiOiJ6aGFuZ1dlaSIsImFnZSI6IjM1In0sImlzcyI6IkFEU1RVRElPIiwiYXVkIjoiQURPTkciLCJpYXQiOjE3MjIzNzA4MzIsIm5iZiI6MTcyMjM3MDgzMiwiZXhwIjoxNzIyMzcwODUyfQ.fLuEHZ_9A0R2bSlBtDl7logBZNtEOT7S5vANvlw5qJU0.088034sShowPageTrace";

    public function login()
    {
        // 不带任何参数 自动定位当前操作的模板文件
        return View::fetch();
    }
    //微信小程序授权登录
    public function miniprogramLogin()
    {
        $token = input('token');
        if (!empty($token)) {
            //解析token
            $key = new Key(md5($this->jwt_secret_key), "HS256");
            try {
                $decode = JWTUtil::decode($token, $key);
                $data = ['code' => '1', 'message' => 'token验证通过'];
                $data = json_encode($data, JSON_UNESCAPED_UNICODE);
                return $data;
                //如果没有过期，则正常处理，如果过期，则抛出异常
            } catch (ExpiredException $e) {
                //捕获异常
                $data = ['code' => '0', 'message' => 'token过期'];
                $data = json_encode($data, JSON_UNESCAPED_UNICODE);
                return $data;
            }
        }
        // 小程序配置信息
        $appid = "wx3ea6ee9cbfefdac7"; // 小程序的appid
        $secret = "babadb0e27fddb5827b61113ddaf934f"; // 小程序的AppSecret
        $code = input('code');
        $avatar = input('avatar');
        $name = input('name');

        // 请求地址
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";

        // 发送GET请求
        $response = file_get_contents($url);
        $response = json_decode($response);
        if (isset($response->errcode)) {
            $data = ['code' => '0', 'message' => '获取openid失败'];
            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
            return $data;
        }
        // 获取openid
        $openid = $response->openid;
        $data = [
            'openid' => $openid,
            'name' => $name,
            'avatar' => $avatar
        ];

        $obj = new Miniuser();
        $user = $obj->searchData($openid);
        if (!empty($user)) {
            //签发token
            $token = $this->createToken(['openid' => $openid], 30);
            $data = ['code' => '1', 'message' => 'openid已存在,登录成功', 'token' => $token];
            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
            return $data;
        }
        $user = $obj->addData($data);
        if ($user != 1) {
            $data = ['code' => '0', 'message' => '数据写入数据库失败'];
            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
            return $data;
        }
        //签发token
        $token = $this->createToken(['openid' => $openid], 30);
        $data = ['code' => '1', 'message' => '登录成功', 'token' => $token];
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        return $data;
    }
    public function information()
    {
        try {
            validate(Abc::class)->batch(true)->check([
                'email' => input('post.email'),
                'name' => input('post.name'),
                'id_card' => input('post.id_card')
            ]);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            dump($e->getError());
            die();
        }
        echo "验证通过！";
    }

    public function shaoBing()
    {
        $arr = [2, 6, 8, 12, 323, 4, 2, 6, 12, 65, 3123, 5646, 23123, 45646, 213, 111];
        for ($i = 0; $arr[$i] != 111; $i++)
            ;
        if ($i == (count($arr) - 1)) {
            echo "查找失败！";
        } else {
            echo "查找成功！";
        }
    }
    //生成token(使用JWT扩展库)
    public function createToken($user, $exptime)
    {


        $key = md5($this->jwt_secret_key);//jwt的签发秘钥
        $time = time();//签发时间
        $expire = $time + $exptime;//过期时间
        $token = array(
            $user,
            "iss" => "ADSTUDIO",//签发组织
            "aud" => "ADONG",//签发作者
            "iat" => $time,
            "nbf" => $time,
            "exp" => $expire
        );
        $jwt = JWTUtil::encode($token, $key, "HS256", 'keyId');
        return $jwt;
    }

    //生成token,并向浏览器输出
    public function token()
    {
        $token = $this->createToken($this->user, $this->exptime);
        echo $token;
    }

    //后端解析token，并判定token是否过期
    public function verifyToken()
    {
        $token = input('token');
        $key = new Key(md5($this->jwt_secret_key), "HS256");

        try {
            $decode = JWTUtil::decode($token, $key);
            //如果没有过期，则正常输出，如果过期，则抛出异常
            echo "token解析成功！<hr>";
            dump($decode);
        } catch (ExpiredException $e) {
            //捕获异常
            echo "token过期！";
            die();
        }
    }

    //模型查询数据
    public function search()
    {
        // 使用查询构造器查询满足条件的数据
        // $user = User::find(31);
        // echo $user->grade;
        foreach (User::where('name', '张伟')->cursor() as $user) {
            echo $user->age . "**";
        }
    }
    //模型新增数据
    public function addData()
    {
        // 使用查询构造器查询满足条件的数据
        $data = [
            'name' => 'Jack',
            'sex' => 'male',
            'age' => '35',
            'grade' => '3'
        ];
        $obj = new User();
        $user = $obj->addData($data);
        echo $user;
    }
    public function show()
    {
        // 不带任何参数 自动定位当前操作的模板文件
        return View::fetch();
    }
    public function verifyCode()
    {
        if (!captcha_check(input('code'))) {
            $data = ["message" => "验证失败"];
            $result = json($data);
            return $result;
        }

        $data = ["message" => "验证成功"];
        $result = json($data);
        return $result;
    }
    //文件上传
    public function upload()
    {

        header('Access-Control-Allow-Origin:*');
        // // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('abc');
        // 上传到本地服务器
        $savename = \think\facade\Filesystem::putFile('topic', $file);
    }
    public function middleWareProcess()
    {
        return "中间件拦截，参数不合法！";
    }
}